<?php

namespace app\admin\controller\mall;

use app\admin\model\MallCate;
use app\admin\model\MallTickets;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * Class Tickets
 * @package app\admin\controller\mall
 * @ControllerAnnotation(title="商城商品管理")
 */
class Tickets extends AdminController
{

    use Curd;

    protected $relation;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallTickets();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where, $order) = $this->buildTableParames();
            $count = MallTickets::with('cate')->where($where)->count();
            $list = MallTickets::with('cate')
                ->where($where)
                ->limit(($page - 1) * $limit, $limit)
                ->order($order)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="入库")
     */
    public function stock($id)
    {
        $row = MallTickets::find($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            try {
                $row->total_stock += $post['stock'];
                $row->stock += $post['stock'];
                $result = $row->save();
            } catch (\Exception $e) {
                $this->error('保存失败');
            }

            if ($result) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }

        $this->assign('row', $row);
        return $this->fetch();
    }
}
